using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Reflection;
using System.IO;
using System.Globalization;

namespace Web.Ajax.Handlers
{
    public class Resource : IHttpHandler
    {
		public bool AllowCache
		{
			get
			{
				return Configuration.Settings.Current.CacheResources;
			}
		}

        public void ProcessRequest(HttpContext c)
        {
            HttpRequest request = c.Request;
            HttpResponse response = c.Response;
            try
            {                
                string qs = request.QueryString.ToString();
                if (string.IsNullOrEmpty(qs))
                    throw new Exception("No Resource Name provided.");
				if (qs == "Null")
				{
					response.AppendHeader("Content-Length", "0");
					response.ContentType = "text/html";
					response.Cache.SetExpires(DateTime.Now.AddYears(1));
					return;
				}

                if (qs.IndexOf('.') == -1)
                    qs = Encryption.Decrypt(c.Server.UrlDecode(qs));

                DateTime st = DateTime.Now;
                Web.Ajax.Resources.Resource r = Web.Ajax.Resources.GetResource(qs);
                double ms = DateTime.Now.Subtract(st).TotalMilliseconds;

                response.ContentType = r.GetContentType();               

                DateTime AssemblyBuildTime = r.GetAssemblyBuildTime();
                
                response.Cache.SetCacheability(HttpCacheability.Private);

				if (!AllowCache)
				{
					response.Cache.SetLastModified(AssemblyBuildTime);
					response.Cache.SetExpires(DateTime.Now.AddDays(-1));
					response.Cache.SetValidUntilExpires(false);
				}
				else
				{
					response.Cache.SetExpires(DateTime.Now.AddHours(6));
					response.Cache.SetValidUntilExpires(true);
				}


                /*
                if (IsImage(response.ContentType))
                {
                    response.Cache.SetValidUntilExpires(true);
                    response.Cache.SetExpires(DateTime.Now.AddMinutes(30));
                }
                */
                

                //If-Modified-Since == AssemblyTime return
                string ModifiedHeader = request.Headers["If-Modified-Since"];
                if (!string.IsNullOrEmpty(ModifiedHeader))
                {
                    DateTime dt = DateTime.Parse(ModifiedHeader, new CultureInfo("en-ie"));
                    if (dt.ToString("dd/MM/yyyy HH:mm:ss") == AssemblyBuildTime.ToString("dd/MM/yyyy HH:mm:ss"))
                    {
                        response.StatusCode = 304;
                        response.SuppressContent = true;
                        return;
                    }
                }//*/
               

                byte[] bytes = r.GetBytes();

                if (bytes == null)
                {
                    response.Write("Error: Resource not found, '" + r.FullName + "'");
                    return;
                }
                response.AppendHeader("Content-Length", bytes.Length.ToString());
                response.OutputStream.Write(bytes, 0, (int)bytes.Length);               
                
            }
            catch (Exception e)
            {
                response.StatusCode = 404;
                response.Write("Error: " + e.Message);                    
            }
        }

        public bool IsImage(string contentType)
        {
            if (string.IsNullOrEmpty(contentType))
                return false;
            if (contentType.StartsWith("image"))
                return true;
            return false;
        }

        public bool IsReusable
        {
            get 
            {
                return true;
            }
        }
    }

}
